package com.wfs.suanfa.nio.xiaoliu.nio1;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {

    public static void fileChannel(){
        try {
            RandomAccessFile randomAccessFile=new RandomAccessFile("D:\\test.txt","rw");
            FileChannel fileChannel=randomAccessFile.getChannel();
            ByteBuffer buffer=ByteBuffer.allocate(1);
            int read1 = fileChannel.read(buffer);
            while (read1!=-1){
                System.out.print(new String(buffer.array()));
                buffer.clear();
                read1 = fileChannel.read(buffer);
            }
            System.out.println();
            //设置指针重新读取数据
            fileChannel.position(0);
            //全量读取
            ByteBuffer bufferAll=ByteBuffer.allocate(Long.valueOf(fileChannel.size()).intValue());
            int read = fileChannel.read(bufferAll);
            System.out.println("读取的数据量：" + read + "，内容为：\r\n" + new String(bufferAll.array()));
            //文件写入
            ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
            writeBuffer.put("\n\n".getBytes());
            writeBuffer.put("java".getBytes());
            //写模式切换为读取
            writeBuffer.flip();
            while(writeBuffer.hasRemaining()) {
                // 将 Buffer 中的内容写入文件
                fileChannel.write(writeBuffer);
            }
            //写入后再次读取
            //设置指针重新读取数据
            fileChannel.position(0);
            //全量读取
            ByteBuffer bufferAll2=ByteBuffer.allocate(Long.valueOf(fileChannel.size()).intValue());
            int read2 = fileChannel.read(bufferAll2);
            System.out.println("读取的数据量：" + read2 + "，内容为：\r\n" + new String(bufferAll2.array()));
            fileChannel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
